package com.eims.sls_app.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import bls.juejin.cn.R;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.VerificationCodeUtils;
import com.eims.sls_app.view.MyToast;

import org.json.JSONException;
import org.json.JSONObject;

public class CheckPhoneNumber extends MyBaseActivity implements View.OnClickListener {
	private Context context = CheckPhoneNumber.this;
	private ImageButton btn_back;
	private EditText check_phone_num_edit, check_phone_ma_edit;
	private Button check_phone_ma_button, check_phone_ok_button;
	private VerificationCodeUtils verificationCodeUtils;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_check_phone_number);
		App.activityS.add(this);
		findView();
		init();
		setListener();
	}

	private void setListener() {
		btn_back.setOnClickListener(this);
		check_phone_ma_button.setOnClickListener(this);
		check_phone_ok_button.setOnClickListener(this);
	}

	private void init() {
		verificationCodeUtils = new VerificationCodeUtils(
				CheckPhoneNumber.this,
				new VerificationCodeUtils.VerificationCodeListener() {
					@Override
					public void onCheckProgress(int status, int progress) {
						if (status == VerificationCodeUtils.FINISHED
								&& progress == -1) {
							check_phone_ma_button.setText("重新获取验证码");
						} else if (status == VerificationCodeUtils.RUNNING) {
							check_phone_ma_button.setText(progress + "秒");
						}
					}

					@Override
					public void onCheckComplete(int params, String result,
							String msg) {
						switch (params) {
						case 0: // 请求短信验证码

							break;
						case 1: // 检查短信验证码
							if (result.equals("0")) {
								setResult();
							}
							break;
						}
					}
				});
	}

	private void findView() {
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		check_phone_num_edit = (EditText) findViewById(R.id.check_phone_num_edit);
		check_phone_ma_edit = (EditText) findViewById(R.id.check_phone_ma_edit);
		check_phone_ma_button = (Button) findViewById(R.id.check_phone_ma_button);
		check_phone_ok_button = (Button) findViewById(R.id.check_phone_ok_button);

	}

	private void setResult() {
		Intent bundle = new Intent();
		bundle.putExtra("mobile", check_phone_num_edit.getText().toString());
		setResult(Activity.RESULT_OK, bundle);
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_check_phone_number, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();

		// noinspection SimplifiableIfStatement
		if (id == R.id.action_settings) {
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.check_phone_ma_button:
			if (checkEdit(check_phone_num_edit, false)) {
				new MyAsynTask().execute(0);
			}
			break;
		case R.id.check_phone_ok_button:
			if (checkEdit(check_phone_num_edit, false)
					&& checkEdit(check_phone_ma_edit, false)) {
				new MyAsynTask().execute(1);
			}
			break;
		}
	}

	/**
	 * 检查输入情况
	 * 
	 * @param v
	 *            指定的控件
	 * @param hasFocus
	 *            true获得焦点，false失去焦点
	 */
	private boolean checkEdit(View v, boolean hasFocus) {
		switch (v.getId()) {
		case R.id.check_phone_num_edit:
			if (!hasFocus) {
				String str = ((EditText) v).getText().toString();
				if (null == str || str.equals("")) {
					((EditText) v).setError("手机号不能为空");
					((EditText) v).setCompoundDrawablesWithIntrinsicBounds(0,
							0, R.drawable.ic_action_error, 0);
				} else if (!LotteryUtils.checkPhoneREX(str)) {
					((EditText) v).setError("手机号码不符合规则");
					((EditText) v).setCompoundDrawablesWithIntrinsicBounds(0,
							0, R.drawable.ic_action_error, 0);
				} else {
					return true;
				}
			}
			break;
		case R.id.check_phone_ma_edit:
			if (!hasFocus) {
				String str = ((EditText) v).getText().toString();
				if (null == str || str.equals("")) {
					((EditText) v).setError("验证码不能为空");
					((EditText) v).setCompoundDrawablesWithIntrinsicBounds(0,
							0, R.drawable.ic_action_error, 0);
				} else {
					return true;
				}
			}
			break;
		}
		return false;
	}

	// 判断是否绑定了手机号码
	class MyAsynTask extends AsyncTask<Integer, Integer, String> {
		private int param;

		@Override
		protected String doInBackground(Integer... params) {
			param = params[0];
			String error = "-1";
			String mOpt = "59";
			String mTime = RspBodyBaseBean.getTime();
			String mImei = RspBodyBaseBean.getIMEI(context);
			String key = MD5.md5(App.MD5_key);
			String mInfo = "{\"mobile\":\""
					+ check_phone_num_edit.getText().toString() + "\"}";
			String mCrc = RspBodyBaseBean
					.getCrc(mTime, mImei, key, mInfo, "-1");
			String mAuth = RspBodyBaseBean.getAuth(mCrc, mTime, mImei, "-1");

			String values[] = { mOpt, mAuth, mInfo };
			String result = HttpUtils.doPost(App.names, values,
					App.path);

			// Log.i("x", "验证手机号info---------" + mInfo);
			Log.e("x", "验证手机号result----" + result);

			if ("-500".equals(result))
				return result;
			try {
				JSONObject ob = new JSONObject(result);
				String hasPhoneNumber = ob.getString("hasPhoneNumber");
				if ("0".equals(hasPhoneNumber)) {
					return App.ERROR_SUCCESS + "";
				}
			} catch (JSONException e) {
				Log.w("TAG", "JSONException==>" + e.toString());
				error = "-1";
			}
			return error;

		}

		@Override
		protected void onPostExecute(String s) {
			super.onPostExecute(s);
			switch (Integer.valueOf(s)) {
			case 0:
				if (param == 0) {
					verificationCodeUtils.startCheck(0, check_phone_num_edit
							.getText().toString());
				} else if (param == 1) {
					verificationCodeUtils.startCheck(1, check_phone_num_edit
							.getText().toString(), check_phone_ma_edit
							.getText().toString());
				}
				break;
			case -1:
				check_phone_num_edit.setError("该手机号码已被绑定");
				check_phone_num_edit.setCompoundDrawablesWithIntrinsicBounds(0,
						0, R.drawable.ic_action_error, 0);
				break;
			case -500:
				MyToast.getToast(context, "验证超时").show();
				break;
			}
		}
	}

}
